import { createRouter, createWebHistory } from 'vue-router'
import { LocalStorageUtils } from '@/utils/StorageUtils.ts'
// import NProgress from 'nprogress'

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: [
		{
			path: '/',
			redirect: '/index'
		},
		{
			path: '/index',
			// route level code-splitting
			// this generates a separate chunk (About.[hash].js) for this route
			// which is lazy-loaded when the route is visited.
			component: () => import('@/views/index.vue')
		},
		{
			path: '/login',
			component: () => import('@/views/login/Login.vue')
		},
		{
			path: '/main',
			component: () => import('@/views/main/main.vue'),
			children: [
				{
					path: '/home',
					component: () => import('@/views/main/home/home.vue')
				}, {
					path: '/system',
					redirect: '/index'
				}, {
					path: '/system/user',
					component: () => import('@/views/main/system/user.vue')
				}, {
					path: '/system/role',
					component: () => import('@/views/main/system/role.vue')
				}, {
					path: '/system/menu',
					component: () => import('@/views/main/system/menu.vue')
				}, {
					path: '/system/dept',
					component: () => import('@/views/main/system/dept.vue')
				}, {
					path: '/device/center',
					component: () => import('@/views/main/device/center.vue')
				}, {
					path: '/device/monitor',
					component: () => import('@/views/main/device/monitor.vue')
				}, {
					path: '/device/manage',
					component: () => import('@/views/main/device/manage.vue')
				}
			]
		},
		{
			path: '/:pathMatch(.*)',
			component: () => import('@/views/pages/404.vue')
		}
	]
})

/*********************************************** 导航守卫 ******************************************************/
//前置路由
// import { userStore } from '../store/userInfo';
// 全局守卫：登录拦截 本地没有存token,请重新登录。
router.beforeEach((to, from, next) => {
	console.log('-----------------------------------全局路由拦截-----------------------------------')
	// console.log('to ===> ', to)
	// console.log('from ===> ', from)
	let token = LocalStorageUtils.getKey('wisdomToken')
	// console.log('token ===>',token)
	console.log('to.path ===>', to.path)
	// console.log('from.path ===>', from.path)
	
	// 未登录，则去登录！
	if (!token) {
		// 登录页。【不拦截页】
		if (to.path == '/login' || to.path == '/' || to.path == '/index') {
			// 登录页，【不拦截页】 直接放行.........
			console.log('登录页/不拦截页')
		} else {
			console.log('未登录！ ======> to 登录页！')
			return router.push('login')
		}
	}
	// else {
	// 	// 登录成功后，更换新 token。
	// 	console.log("更换token。")
	// 	localStorage.setItem('wisdomToken', token)
	// }
	console.log('-----------------------------------全局路由拦截-----------------------------------')
	next()
})

router.afterEach(() => {
	// NProgress.done()
})

router.onError((error) => {
	console.error('路由错误:', error)
	// NProgress.done()
})




export default router
